package data

import (
	"commerce/common"
	"commerce/model"
	"fmt"
	"strings"
	"time"
)

func PageFeedback(pageNo, pageSize int, name string) (*common.Page, error) {

	whereSql := composeFdSearchQuerySql(name)

	row := common.DB.QueryRow("select count(*) FROM feed_back" + whereSql)
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, member_id, member_name, member_ip, phone, content, `type`, created_time FROM feed_back" + whereSql + " LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var fs []model.Feedback
	for rows.Next() {
		f := model.Feedback{}
		if err := rows.Scan(&f.Id, &f.MemberId, &f.MemberName, &f.MemberIp, &f.Phone, &f.Content, &f.Type, &f.CreatedTimeStr); err != nil {
			return nil, fmt.Errorf("反馈分页数据有误:%s", err.Error())
		}
		f.TypeStr = common.GetFd()[f.Type]
		fs = append(fs, f)
	}
	return common.NewPage(fs, pageNo, pageSize, totalRecords), nil
}

func AddFeedback(f model.Feedback) (int, error) {

	stmt, err := common.DB.Prepare(`insert into feed_back(member_id, member_name, member_ip, phone, content, type, created_time) VALUES (?, ?, ?, ?, ?, ?, ?)`)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(f.MemberId, f.MemberName, f.MemberIp, f.Phone, f.Content, f.Type, time.Now().Add(8*time.Hour))

	if err != nil {
		return 0, fmt.Errorf("save feedback err: %v", err)
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save feedback insert id err: %v", err)
	}
	return int(id), nil
}

func DeleteFeedback(id int) error {

	stmt, err := common.DB.Prepare("update feed_back set is_valid = 0 WHERE id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(id)

	return err
}

func composeFdSearchQuerySql(name string) string {

	// 没有条件查询
	if len(name) == 0 {
		return ""
	}
	sb := strings.Builder{}
	search := "'" + strings.TrimSpace(name) + "%'"
	sb.WriteString(" WHERE (member_name like " + search + " OR content like " + search + ") and is_valid = 1 ")

	return sb.String()
}
